import { login, getInfo } from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  // getCookieToJSON,
  // setCookie,
} from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  userinfo: {}, // getCookieToJSON('userinfo') || {},
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    token ? setToken(token, 1) : removeToken()
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERINFO: (state, data) => {
    if (!data || !data.user_name) {
      state.userinfo = {}
      return
    }
    const userinfo = {
      name: data.user_name,
      avatar: data.avatar,
      company: data.sp_name,
      role: data.role_name,
      email: data.email,
      balance: data.balance,
      freeze: data.freeze,
      handle: data.handle,
    }
    state.userinfo = userinfo
    // setCookie('userinfo', userinfo)
  },
}

const actions = {
  // user login
  async login({ commit, dispatch }, userInfo) {
    await dispatch('logout')
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then(({ data }) => {
          const { xz_token: token } = data
          commit('SET_TOKEN', token)

          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response

          commit('SET_USERINFO', data)
          resolve(data)
        })
        .catch(_ => {
          reject(false)
        })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_USERINFO', {})
      commit('SET_ROLES', [])
      commit('permission/SET_ROUTES', [], { root: true })

      resetRouter()

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USERINFO', {})
      commit('SET_ROLES', [])
      commit('permission/SET_ROUTES', [], { root: true })

      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true,
    })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
